package com.wk.code.wkserver.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.FileInputStream;

/**
 * @version: 2.4.5
 * @author: wq
 * @time: 2021/2/3 11:36
 */
public class QiniuUtils {

    /**
     * 设置需要操作的账号的AK和SK
     */
    private static final String ACCESS_KEY = "v3aJTJ71ONbM3hWtHg8lW3hr0dsNHM7KUp3otUUQ";
    private static final String SECRET_KEY = "wR4rsiHg_BIc3Bd8oCkySEtYOwLQTMj4jvhrpQHw";

    /**
     * 要上传的空间名称
     */
    private static final String BUCKETNAME = "wkzj-boss";

    /**
     * 密钥
     */
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 外链默认域名
    private static final String DOMAIN = "http://bossbyte.wkhelpme.com";


    /**
     * 将图片上传到七牛云
     */
    public static String uploadQNImg(FileInputStream file, String key) {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            String upToken = auth.uploadToken(BUCKETNAME);
            try {
                Response response = uploadManager.put(file, key, upToken, null, null);
                DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
                return DOMAIN + "/" + putRet.key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
